package com.pwser.zk;

import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

public class SimpleZkClient {
	private static final String connectString = "192.168.33.102:2181,192.168.33.103:2181,192.168.33.104:2181";
	private static final int sessionTimeout = 2000;
	private ZooKeeper zkClient = null;
	
	@Before
	public void ini() throws Exception {
		zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				//监听事件处理逻辑
				System.out.println(event.getType() + "---" + event.getPath());
				try {
					zkClient.getChildren("/", true);
				} catch (KeeperException | InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		
		//this.createNode();
	}
	
	/**
	 * 创建节点及数据
	 * @throws Exception 
	 */
	public String createNode() throws Exception  {
		String nodeCreated = zkClient.create("/eclipse", "测试数据".getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		return nodeCreated;
	}
	
	/**
	 * 查看节点是否存在
	 * @throws Exception 
	 */
	@Test
	public void existsNode() throws Exception  {
		Stat stat = zkClient.exists("/eclipse", false);
		if(stat != null){
			System.out.println(stat.toString());
		}else{
			System.out.println("node is not exists");
		}
	}
	
	/**
	 * 获取子节点
	 * @throws Exception 
	 */
	@Test
	public void getChildren() throws Exception {
		List<String> childrenList = zkClient.getChildren("/", true);
		for (String children : childrenList) {
			System.out.println(children);
		}
		//Thread.sleep(Long.MAX_VALUE);
	}
	
	/**
	 * 获取节点数据
	 * @throws Exception 
	 */
	@Test
	public void getNodeData() throws Exception {
		byte[] data = zkClient.getData("/eclipse", false, null);
		System.out.println(new String(data, "UTF-8"));
	}
	
	/**
	 * 删除节点
	 * @throws Exception 
	 */
	//@Test
	public void delNode() throws Exception {
		zkClient.delete("/test2", -1);
		System.out.println("删除节点成功！");
	}
	
	/**
	 * 修改节点数据
	 * @throws Exception 
	 */
	@Test
	public void setNode() throws Exception {
		Stat stat = zkClient.setData("/eclipse", "测试数据-1111".getBytes(), -1);
		System.out.println("修改节点成功！");
	}
}
